--[[
	获取邮件列表
]]
local filename = "getmaillist.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog =require "filelog"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

local service = nil
local CMD = {
	service = nil
}

-- socket传来的请求，可以获取邮件列表
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end
	local maillist = {}
	local result = cluster.call("datanode", ".router", "select_rk", rid, "rm_mail")
    if not result or not result[2] then
        return {maillist = maillist}
    end

    --删除过期邮件
    local limit = 20    --不超过20封，不删除
    if result[1] and result[1] > limit then
        local curtime = timetool.get_time()
        local outtime = curtime - 3600 * 48
	    for k,v in pairs(result[2]) do
		    if v.create_time < outtime then
                local attach_json = json.decode(v.attach_json)
                if not attach_json or not attach_json.diamond then
                    cluster.send("datanode", ".router", "delete_rk", rid, "rm_mail", v.keyid)
                    result[2][k] = nil
                end
		        
           end
	    end
    end

	local i = 1
	for k,v in pairs(result[2]) do
		maillist[i] = {}
		maillist[i].keyid		= v.keyid
		maillist[i].sendrid		= v.sendrid
		maillist[i].sendname	= v.sendname
		maillist[i].subject		= v.subject
		maillist[i].content		= v.content
		maillist[i].attach_json	= v.attach_json
		maillist[i].mail_type	= v.mail_type
        maillist[i].create_time	= v.create_time
		i = i+1
	end
	result = cluster.call("datanode", ".router", "update_rk", rid, "rs_readmail", 0, {last_gettime=timetool.get_time()})

	return {maillist = maillist}
end

return CMD
